﻿using shop.Bll;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using unvell.ReoGrid;
using shop.Bll.Logi;
using CommonTools;
using CommonTools.Controls;
using shop.daifa;
using Flurl.Http;
using unvell.ReoGrid.IO.OpenXML.Schema;
using shop.job;

namespace shop.Logi
{
    public partial class RefundRegistRptForm : DockContent
    {

        shop.Bll.RefundRegistBll _bll = new shop.Bll.RefundRegistBll();
        int _row = -1;

        GridDataBuilder<object> _builder;


        public RefundRegistRptForm()
        {
            InitializeComponent();
            this.box_begin.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
            this.box_end.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month));
        }

        private async void btn_Query_Click(object sender, EventArgs e)
        {
            var pr = new RefundRegQueryDto()
            {
                Begin = box_begin.Value.Value,
                End = box_end.Value.Value,
                IsSendMessage = box_onlyNotSend.Checked ? false : (bool?)null,
                FUser = UserBll.CurrentUser.Name,
                UserId = UserBll.CurrentUser.DocID.ToString(),
                Shop= box_shop.Text.Trim(),
                platform_goods_id= box_id.Text.Trim(),
                Stock= box_stock.Text.Trim(),
            };

            var res = await WaitUI.RunAsync(async () =>
            {
                return (await _bll.QueryList(pr));
            });


            _builder = new GridDataBuilder(this.grid)
                .UseData(res)
                .AutoCreateColumns()
                .UseFilter();

            var rng = _builder.End();

            this.grid.CurrentWorksheet.HideColumns(0,1);

            if (res == null || res.Any() == false )
            {
                _row = 0;
                MessageBox.Show("没有查询到数据", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                _row = res.Count();
            }
        }



        private void btn_selectall_Click(object sender, EventArgs e)
        {
            if(_row<= 0)
            {
                MessageBox.Show("请先查询!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }


            for (int i = 1;i<= _row; i++)
            {
                grid[1, i] = true;
            }
        }

        private void btn_images_Click(object sender, EventArgs e)
        {
            if(this.grid.CurrentCell == null || grid.CurrentCell.Row<=0)
            {
                return;
            }

            var id = grid[0, grid.CurrentCell.Row].IsNull(0); 
            if(id<=0)
            {
                return;
            }

            var form = new RefundImagesForm();
            form.DocId = id;
            form.ShowDialog();  
        }

        private void btn_export_Click(object sender, EventArgs e)
        {
            //var bl = box_onlyNotSend.Checked ? false : (bool?)null;

            //var dialog = new FolderBrowserDialog();
            //if(dialog.ShowDialog() != DialogResult.OK)
            //{
            //    return;
            //}

            //var file = await WaitUI.RunAsync(async ()=> await myApp.GetClient().Request("RefundRegist/Export")
            //    .AppendQueryParam("begin", this.box_begin.Value.ToDate())
            //    .AppendQueryParam("end", this.box_end.Value.LastTimeOfDay())
            //    .AppendQueryParam("isSendMessage", bl)
            //    .DownloadFileAsync(dialog.SelectedPath));

            //Process.Start(file);

            var begin = box_begin.Value.Value.Date;
            var end = box_end.Value.Value.Date.LastTimeOfDay();




            new PopSelector<string>()
                .AddItem("插入图片", a => a)
                .AddItem("插入链接", a => a)
                .ShowPop(this.btn_export, async a =>
                {
                    var pr = new RefundRegQueryDto()
                    {
                        Begin = begin,
                        End = end,
                        IsSendMessage = box_onlyNotSend.Checked ? false : (bool?)null,
                        FUser = UserBll.CurrentUser.Name,
                        UserId = UserBll.CurrentUser.DocID.ToString(),
                        Shop = box_shop.Text.Trim(),
                        platform_goods_id = box_id.Text.Trim(),
                        Stock = box_stock.Text.Trim(),
                    };

                    pr.UsePicLink = a == "插入链接";

                    try
                    {
                        await myApp.GetClient().Request("RefundRegist/ExportTask")
                            .PostJsonAsync(pr);
                            
                        MessageBox.Show("任务已创建", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        //打开任务窗体
                        myApp.OpenJobsForm();

                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                    }

                });
         


        }

        private void grid_RangeEndEdit(object sender, unvell.ReoGrid.Events.RangeEventArgs e)
        {
            if(e.Range == null)
            {
                return;
            }

            if(_builder == null)
            {
                return;
            }

            for (int i = e.Range.Row; i <= e.Range.EndRow; i++)
            {
                //if(e.)
            }

            var sc = this.grid.GetColumnHeader("是否已发送消息");
            var haveRight =-1;

            e.IterateCells(this.grid, (r, c, cell) => {

                if (c == sc.Index)
                {
                    if (haveRight < 0)
                    {
                        //检查权限
                        haveRight = CommonTools.CommonConfig.CheckRight("03.11.5") ? 1 : 0;
                    }

                    if (haveRight == 1)
                    {
                        var id = grid[0, r].IsNull(0);

                        _bll.SetSendStatus(id, grid[cell].IsNull(false));
                        MessageTip.ShowOk(this, "修改完成");
                    }
                    else
                    {
                        MessageBox.Show("对不起, 您没有权限!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            });


        }

        private async void btn_delete_Click(object sender, EventArgs e)
        {

            var list = new List<int>();

            for (int i = grid.BindingStartRow; i < this.grid.CurrentWorksheet.RowCount; i++)
            {
                if (grid[1,i].IsNull(false) == true)
                {
                    list.Add(grid[0, i].IsNull(0));
                }
            }

            if(list.Count == 0)
            {
                MessageBox.Show("请勾选需要操作的项目", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if(MessageBox.Show($"确认要删除{list.Count}条数据", Properties.Resources.systemInformation, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                != DialogResult.Yes)
            {
                return;
            }

            var res = await _bll.DeleteItems(list);
            if (res.IsOk)
            {
                // 刷新
                this.btn_Query_Click(null, e);
            }
            else
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
    }
}
